package com.cswangdao.service.impl;

import com.aliyun.oss.AliOssUtil;
import com.cswangdao.domain.dto.StoragePageDTO;
import com.cswangdao.domain.po.Storage;
import com.cswangdao.mapper.MarketStorageMapper;

import com.cswangdao.result.PageResult;
import com.cswangdao.service.StorageService;


import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.session.SqlSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;


import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;
import java.io.*;
import java.net.URLEncoder;
import java.util.Date;
import java.util.Properties;
import java.util.UUID;

@Service
@Slf4j
@Transactional
public class StorageServiceImpl implements StorageService {

    @Autowired
    private MarketStorageMapper mapper;


    @Autowired
    private AliOssUtil aliOssUtil;



    /**
     * @description: 文件上传
     * @param: file
     * @return: com.cswangdao.domain.po.Storage
     */
    @Override
    public Storage upload(MultipartFile file) throws IOException {
        //随机生成uuid
        String uuid = String.valueOf(UUID.randomUUID());

        //获取文件信息
        String name = file.getOriginalFilename();
        String type = file.getContentType();
        int size =(int) file.getSize();
        //使用uuid生成新的文件名
        int index = name.lastIndexOf(".");
        String newName = uuid+name.substring(index);
        log.info("newFile:{}",newName);
        //生成url
      //  String url = "http://localhost:8083/admin/storage/fetch/"+newName;
        String url =aliOssUtil.upload(file.getBytes(), newName);

        //写入磁盘
       /* try {
            file.transferTo(new File(filePath,newName));
        } catch (IOException e) {
            throw new RuntimeException("文件上传失败");
        }*/
        Storage fileInfo = Storage.builder()
                .key(uuid)
                .name(name)
                .type(type)
                .size(size)
                .url(url)
                .addTime(new Date())
                .updateTime(new Date())
                .build();
        mapper.addFileInfo(fileInfo);

        return fileInfo;


    }

    /**
     * @description: 文件下载
     * @param: uri ，resp
     * @return: void
     */
//    @Override
//    public void dowanload(String fileName, HttpServletResponse resp) {
//        log.error("filePath:{}",filePath);
//
//        //2.获取uuid
//        String uuid = fileName.substring(0,fileName.lastIndexOf("."));
//      //  MarketStorageMapper mapper = MapperUtil.getMapper(MarketStorageMapper.class);
//        //3.查询文件真实名称
//        String name = mapper.getNameByUUID(uuid);
//        try (FileInputStream fis = new FileInputStream(new File(filePath,fileName))) {
//            //设置响应内容类型
//            resp.setContentType("application/octet-stream;charset=utf-8");
//            //设置响应头信息
//            resp.setHeader("content-Disposition", "attachment;filename="+ URLEncoder.encode(name, "UTF-8"));
//
//            byte[] bytes = new byte[1024];
//            int len;
//            //从磁盘读取文件
//            while((len = fis.read(bytes)) != -1){
//                //写回给浏览器
//                resp.getOutputStream().write(bytes,0,len);
//            }
//        } catch (FileNotFoundException e) {
//            throw new RuntimeException(e);
//        } catch (IOException e) {
//            throw new RuntimeException(e);
//        }
//
//    }

    @Override
    public PageResult<Storage> pageQueryInfo(StoragePageDTO pageDTO) {
        PageHelper.startPage(pageDTO.getPage(),pageDTO.getLimit());
        Page<Storage> page = mapper.pageQueryInfo(pageDTO);
        PageResult<Storage> result = PageResult.result(page);
        return result;
    }

    @Override
    public void deleteById(Integer id) {
        mapper.deleteById(id);
    }

    @Override
    public void updateById(Storage storage) {
        mapper.updateById(storage);
    }
}
